<template>
  <div class="settings-page">
    <div class="settings-sidebar">
      <div class="sidebar-header">
        <div class="back-button" @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
        </div>
        <h2 class="sidebar-title">{{ t('settings.title') }}</h2>
      </div>
      <el-menu
        :default-active="activeMenu"
        class="settings-menu"
        @select="handleMenuSelect"
      >
        <el-menu-item index="general">
          <el-icon><Setting /></el-icon>
          <span>{{ t('settings.general') }}</span>
        </el-menu-item>
        <el-menu-item index="editor">
          <el-icon><Edit /></el-icon>
          <span>{{ t('settings.editorSettings') }}</span>
        </el-menu-item>
        <el-menu-item index="appearance">
          <el-icon><View /></el-icon>
          <span>{{ t('settings.appearance') }}</span>
        </el-menu-item>
        <el-menu-item index="buckets">
          <el-icon><Folder /></el-icon>
          <span>{{ t('settings.buckets') }}</span>
        </el-menu-item>
        <el-menu-item index="dataSource">
          <el-icon><Connection /></el-icon>
          <span>{{ t('settings.dataSource') }}</span>
        </el-menu-item>
        <el-menu-item index="about">
          <el-icon><InfoFilled /></el-icon>
          <span>{{ t('settings.about') }}</span>
        </el-menu-item>
      </el-menu>
    </div>
    
    <div class="settings-content">
      <div v-if="activeMenu === 'general'" class="settings-section">
        <h2 class="section-title">{{ t('settings.general') }}</h2>
        <el-divider />
        
        <el-form :model="form" label-width="180px" label-position="left">
          <el-form-item :label="t('settings.language')">
            <el-select v-model="form.language" style="width: 100%">
              <el-option label="中文" value="zh-CN" />
              <el-option label="English" value="en-US" />
            </el-select>
          </el-form-item>
          
          <!-- 特定字段时间格式设置 -->
          <el-divider>{{ t('settings.timeTypeFormats') }}</el-divider>
          
          <!-- 开始时间格式 -->
          <el-collapse accordion>
            <el-collapse-item :title="t('settings.startTimeFormat')">
              <el-form-item :label="t('settings.dateFormat')">
                <el-select v-model="form.startTimeFormat.dateFormat" style="width: 100%">
                  <el-option label="YYYY-MM-DD" value="YYYY-MM-DD" />
                  <el-option label="MM/DD/YYYY" value="MM/DD/YYYY" />
                  <el-option label="DD/MM/YYYY" value="DD/MM/YYYY" />
                  <el-option label="YYYY年MM月DD日" value="YYYY年MM月DD日" />
                  <el-option label="DD MMM YYYY" value="DD MMM YYYY" />
                  <el-option label="MMM DD, YYYY" value="MMM DD, YYYY" />
                </el-select>
              </el-form-item>
              
              <el-form-item :label="t('settings.timeFormat')">
                <el-select v-model="form.startTimeFormat.timeFormat" style="width: 100%">
                  <el-option :label="t('settings.time24Hour')" value="24" />
                  <el-option :label="t('settings.time12Hour')" value="12" />
                </el-select>
              </el-form-item>
              
              <el-form-item :label="t('settings.showTime')">
                <el-switch v-model="form.startTimeFormat.showTime" />
                <el-tooltip :content="t('settings.showTimeTip')" placement="top">
                  <el-icon class="tip-icon"><QuestionFilled /></el-icon>
                </el-tooltip>
              </el-form-item>
              
              <el-form-item :label="t('settings.showSeconds')" v-if="form.startTimeFormat.showTime">
                <el-switch v-model="form.startTimeFormat.showSeconds" />
              </el-form-item>
            </el-collapse-item>
            
            <!-- 创建时间格式 -->
            <el-collapse-item :title="t('settings.createdTimeFormat')">
              <el-form-item :label="t('settings.dateFormat')">
                <el-select v-model="form.createdTimeFormat.dateFormat" style="width: 100%">
                  <el-option label="YYYY-MM-DD" value="YYYY-MM-DD" />
                  <el-option label="MM/DD/YYYY" value="MM/DD/YYYY" />
                  <el-option label="DD/MM/YYYY" value="DD/MM/YYYY" />
                  <el-option label="YYYY年MM月DD日" value="YYYY年MM月DD日" />
                  <el-option label="DD MMM YYYY" value="DD MMM YYYY" />
                  <el-option label="MMM DD, YYYY" value="MMM DD, YYYY" />
                </el-select>
              </el-form-item>
              
              <el-form-item :label="t('settings.timeFormat')">
                <el-select v-model="form.createdTimeFormat.timeFormat" style="width: 100%">
                  <el-option :label="t('settings.time24Hour')" value="24" />
                  <el-option :label="t('settings.time12Hour')" value="12" />
                </el-select>
              </el-form-item>
              
              <el-form-item :label="t('settings.showTime')">
                <el-switch v-model="form.createdTimeFormat.showTime" />
                <el-tooltip :content="t('settings.showTimeTip')" placement="top">
                  <el-icon class="tip-icon"><QuestionFilled /></el-icon>
                </el-tooltip>
              </el-form-item>
              
              <el-form-item :label="t('settings.showSeconds')" v-if="form.createdTimeFormat.showTime">
                <el-switch v-model="form.createdTimeFormat.showSeconds" />
              </el-form-item>
            </el-collapse-item>
            
            <!-- 更新时间格式 -->
            <el-collapse-item :title="t('settings.updatedTimeFormat')">
              <el-form-item :label="t('settings.dateFormat')">
                <el-select v-model="form.updatedTimeFormat.dateFormat" style="width: 100%">
                  <el-option label="YYYY-MM-DD" value="YYYY-MM-DD" />
                  <el-option label="MM/DD/YYYY" value="MM/DD/YYYY" />
                  <el-option label="DD/MM/YYYY" value="DD/MM/YYYY" />
                  <el-option label="YYYY年MM月DD日" value="YYYY年MM月DD日" />
                  <el-option label="DD MMM YYYY" value="DD MMM YYYY" />
                  <el-option label="MMM DD, YYYY" value="MMM DD, YYYY" />
                </el-select>
              </el-form-item>
              
              <el-form-item :label="t('settings.timeFormat')">
                <el-select v-model="form.updatedTimeFormat.timeFormat" style="width: 100%">
                  <el-option :label="t('settings.time24Hour')" value="24" />
                  <el-option :label="t('settings.time12Hour')" value="12" />
                </el-select>
              </el-form-item>
              
              <el-form-item :label="t('settings.showTime')">
                <el-switch v-model="form.updatedTimeFormat.showTime" />
                <el-tooltip :content="t('settings.showTimeTip')" placement="top">
                  <el-icon class="tip-icon"><QuestionFilled /></el-icon>
                </el-tooltip>
              </el-form-item>
              
              <el-form-item :label="t('settings.showSeconds')" v-if="form.updatedTimeFormat.showTime">
                <el-switch v-model="form.updatedTimeFormat.showSeconds" />
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
          
          <el-form-item :label="t('settings.pageSize')">
            <el-input-number v-model="form.pageSize" :min="5" :max="50" :step="5" />
            <el-tooltip :content="t('settings.pageSizeTip')" placement="top">
              <el-icon class="tip-icon"><QuestionFilled /></el-icon>
            </el-tooltip>
          </el-form-item>
          
          <el-form-item :label="t('settings.pageSizeOptions')">
            <div class="page-size-options-container">
              <div class="page-size-select-area">
                <div class="tag-list">
                  <el-empty 
                    v-if="form.pageSizeOptions.length === 0" 
                    :image-size="60" 
                    :description="t('settings.noOptionsSelected')" 
                  />
                  <el-tag
                    v-for="option in sortedPageSizeOptions"
                    :key="option"
                    closable
                    @close="removePageSizeOption(option)"
                    class="page-size-tag"
                    type="info"
                    effect="light"
                  >
                    {{ option }}
                  </el-tag>
                </div>
                <div class="custom-page-size">
                  <el-input-number 
                    v-model="customPageSize" 
                    :min="1" 
                    :max="1000"
                    :step="1" 
                    :placeholder="t('settings.customPageSize')"
                    controls-position="right"
                    size="small"
                  />
                  <el-button 
                    type="primary"
                    size="small"
                    plain
                    @click="addCustomPageSize" 
                    :disabled="!customPageSize || form.pageSizeOptions.includes(customPageSize)"
                    :title="t('settings.addCustomPageSize')"
                  >
                    {{ t('settings.add') }}
                  </el-button>
                </div>
              </div>
              <div class="quick-options">
                <span class="quick-option-label">{{ t('settings.quickOptions') }}:</span>
                <el-button 
                  v-for="option in defaultOptions" 
                  :key="option"
                  type="info"
                  size="small"
                  plain
                  :disabled="form.pageSizeOptions.includes(option)"
                  @click="addDefaultOption(option)"
                  class="quick-option-button"
                >
                  {{ option }}
                </el-button>
              </div>
            </div>
            <el-tooltip :content="t('settings.pageSizeOptionsTip')" placement="top">
              <el-icon class="tip-icon"><QuestionFilled /></el-icon>
            </el-tooltip>
          </el-form-item>
          
          <el-form-item :label="t('settings.maxLoadPages')">
            <el-input-number v-model="form.maxLoadPages" :min="1"  :step="1" />
            <el-tooltip :content="t('settings.maxLoadPagesTip')" placement="top">
              <el-icon class="tip-icon"><QuestionFilled /></el-icon>
            </el-tooltip>
          </el-form-item>
          
          <!-- 添加外部链接打开方式设置 -->
          <el-divider>{{ t('settings.externalLinkOpenModeTitle') }}</el-divider>
          
          <el-form-item :label="t('settings.externalLinkOpenMode')">
            <el-radio-group v-model="form.externalLinkOpenMode">
              <el-radio value="browser">{{ t('settings.externalLinkOpenModeBrowser') }}</el-radio>
              <el-radio value="internal">{{ t('settings.externalLinkOpenModeInternal') }}</el-radio>
            </el-radio-group>
            <el-tooltip :content="t('settings.externalLinkOpenModeTip')" placement="top">
              <el-icon class="tip-icon"><QuestionFilled /></el-icon>
            </el-tooltip>
          </el-form-item>
        </el-form>
      </div>
      
      <div v-if="activeMenu === 'editor'" class="settings-section">
        <h2 class="section-title">{{ t('settings.editorSettings') }}</h2>
        <el-divider />
        
        <el-form :model="form" label-width="180px" label-position="left">
          
          <el-form-item :label="t('settings.uploadUrl')">
            <el-input v-model="form.uploadUrl" :placeholder="t('settings.uploadUrlPlaceholder')" />
            <el-tooltip :content="t('settings.uploadUrlTip')" placement="top">
              <el-icon class="tip-icon"><QuestionFilled /></el-icon>
            </el-tooltip>
          </el-form-item>
          
          <el-form-item :label="t('settings.token')">
            <el-input v-model="form.token" :placeholder="t('settings.tokenPlaceholder')" show-password />
            <el-tooltip :content="t('settings.tokenTip')" placement="top">
              <el-icon class="tip-icon"><QuestionFilled /></el-icon>
            </el-tooltip>
          </el-form-item>
          
          <el-form-item :label="t('settings.autoSave')">
            <el-switch v-model="form.autoSave" />
            <el-tooltip :content="t('settings.autoSaveTip')" placement="top">
              <el-icon class="tip-icon"><QuestionFilled /></el-icon>
            </el-tooltip>
          </el-form-item>
          
          <el-form-item :label="t('settings.autoSaveInterval')" v-if="form.autoSave">
            <el-input-number v-model="form.autoSaveInterval" :min="1" :max="60" :step="1" />
            <span class="input-addon">{{ t('settings.minutes') }}</span>
          </el-form-item>
        </el-form>
      </div>
      
      <div v-if="activeMenu === 'appearance'" class="settings-section">
        <h2 class="section-title">{{ t('settings.appearance') }}</h2>
        <el-divider />
        
        <el-form :model="form" label-width="180px" label-position="left">

        </el-form>
      </div>
      
      <div v-if="activeMenu === 'buckets'" class="settings-section">
        <h2 class="section-title">{{ t('settings.buckets') }}</h2>
        <el-divider />
        
        <div class="bucket-table-container">
          <el-table :data="buckets" border style="width: 100%">
            <!-- <el-table-column prop="id" label="ID" width="280" /> -->
            <el-table-column prop="name" :label="t('settings.bucketName')"   />
            <el-table-column :label="t('settings.createdTime')"  >
              <template #default="scope">
                {{ formatTimeFieldSync(scope.row.created, 'created') }}
              </template>
            </el-table-column>
            <el-table-column :label="t('settings.updatedTime')">
              <template #default="scope">
                {{ formatTimeFieldSync(scope.row.updated, 'updated') }}
              </template>
            </el-table-column>
            <el-table-column :label="t('settings.operations')" width="120">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  circle
                  @click.stop="handleDeleteBucket(scope.row.id)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="bucket-add">
            <el-input 
              v-model="newBucketName" 
              :placeholder="t('settings.bucketNamePlaceholder')"
              maxlength="50"
              show-word-limit
              @keyup.enter="handleAddBucket"
            />
            <el-button type="primary" @click="handleAddBucket">
              {{ t('settings.addBucket') }}
            </el-button>
          </div>
        </div>
      </div>
      
      <div v-if="activeMenu === 'dataSource'" class="settings-section">
        <DataSourceSettings />
      </div>
      
      <div v-if="activeMenu === 'about'" class="settings-section">
        <h2 class="section-title">{{ t('settings.about') }}</h2>
        <el-divider />
        
        <div class="about-content">
          <div class="app-logo">
            <img src="/vite.svg" alt="App Logo" height="80" />
          </div>
          <h3>My Noted</h3>
          <p class="version">{{ t('settings.version') }}: 1.0.0</p>
          <p>{{ t('settings.appDescription') }}</p>
          
          <div class="about-links">
            <a href="#" @click.prevent="openGiteeRepo">Gitee</a>
            <a href="#" @click.prevent>{{ t('settings.checkUpdates') }}</a>
            <a href="#" @click.prevent>{{ t('settings.feedback') }}</a>
          </div>
        </div>
      </div>
      
      <div class="settings-actions">
        <el-button @click="resetSettings">{{ t('settings.reset') }}</el-button>
        <el-button type="primary" @click="saveSettings">{{ t('common.save') }}</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed, onActivated } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft, Setting, Edit, View, InfoFilled, Delete, Folder, Connection, QuestionFilled } from '@element-plus/icons-vue';
import { getAllBuckets, saveBuckets, addBucket, deleteBucket, BucketItem } from '../utils/bucketManager';
import DataSourceSettings from '../components/settings/DataSourceSettings.vue';
import { getConfig, saveConfig } from '../services/configService';
import { formatTimeFieldSync } from '../utils/dateFormatter';
import { openExternalUrl } from '../utils/urlHandler';

const { t, locale } = useI18n();
const router = useRouter();
const route = useRoute();
const activeMenu = ref('general');

// 自定义分页大小
const customPageSize = ref<number | undefined>(null as unknown as undefined);

// 默认选项列表
const defaultOptions = [5, 10, 15, 20, 30, 50, 100];

// 自定义选项 - 过滤出不在默认选项中的值
const customOptions = computed(() => {
  return form.pageSizeOptions.filter(option => !defaultOptions.includes(option));
});

// 排序后的分页选项
const sortedPageSizeOptions = computed(() => {
  return [...form.pageSizeOptions].sort((a, b) => a - b);
});

// 桶管理相关变量
const buckets = ref<BucketItem[]>([]);
const newBucketName = ref('');

// 设置表单
const form = reactive({
  // 通用设置
  language: localStorage.getItem('language') || 'zh-CN',
  pageSize: 15,
  pageSizeOptions: [10, 15, 20, 50],
  maxLoadPages: 10,
  externalLinkOpenMode: 'browser' as 'browser' | 'internal',
  
  // 编辑器设置
  uploadUrl: '',
  token: '',
  defaultEditorMode: 'richText',
  autoSave: true,
  autoSaveInterval: 5,
  
  // 外观设置
  theme: 'system',
  fontSize: 'medium',
  fontFamily: 'system',
  
  // 特定字段时间格式设置
  startTimeFormat: {
    dateFormat: 'YYYY-MM-DD',
    timeFormat: '24',
    showTime: true,
    showSeconds: true
  },
  createdTimeFormat: {
    dateFormat: 'YYYY-MM-DD',
    timeFormat: '24',
    showTime: true,
    showSeconds: true
  },
  updatedTimeFormat: {
    dateFormat: 'YYYY-MM-DD',
    timeFormat: '24',
    showTime: true,
    showSeconds: true
  }
});

// 监听语言变化
watch(() => form.language, (newVal) => {
  locale.value = newVal;
});

// 菜单选择处理
const handleMenuSelect = (key: string) => {
  activeMenu.value = key;
};

// 加载桶列表
const loadBuckets = () => {
  buckets.value = getAllBuckets();
};

// 在系统浏览器中打开Gitee仓库
const openGiteeRepo = async () => {
  try {
    await openExternalUrl('https://gitee.com/li_shi_sheng/my-noted');
  } catch (error) {
    console.error('打开外部URL失败:', error);
    ElMessage.error(t('errors.openUrlError'));
  }
};

// 添加桶名称
const handleAddBucket = () => {
  const bucketNameTrimmed = newBucketName.value.trim();
  
  if (!bucketNameTrimmed) {
    ElMessage.warning(t('settings.bucketNameEmpty'));
    return;
  }
  
  if (bucketNameTrimmed.length > 50) {
    ElMessage.warning(t('settings.bucketNameTooLong'));
    return;
  }
  
  if (addBucket(bucketNameTrimmed)) {
    loadBuckets();
    newBucketName.value = '';
    ElMessage.success(t('settings.bucketAddSuccess'));
  } else {
    ElMessage.error(t('settings.bucketAddFailed'));
  }
};

// 删除桶名称
const handleDeleteBucket = (bucketId: string) => {
  const bucket = buckets.value.find(b => b.id === bucketId);
  if (!bucket) return;
  
  ElMessageBox.confirm(
    t('settings.bucketDeleteConfirm', { name: bucket.name }),
    t('common.confirm'),
    {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning',
    }
  ).then(() => {
    if (deleteBucket(bucketId)) {
      loadBuckets();
      ElMessage.success(t('settings.bucketDeleteSuccess'));
    } else {
      ElMessage.error(t('settings.bucketDeleteFailed'));
    }
  }).catch(() => {
    // 用户取消删除
  });
};

// 保存配置到electron
const saveSettings = async () => {
  try {
    // 保存语言设置（仍然使用localStorage以便前端可以直接访问）
    localStorage.setItem('language', form.language);
    
    // 获取当前配置
    const config = await getConfig();
    
    // 创建特定时间格式设置的深拷贝
    const startTimeFormat = JSON.parse(JSON.stringify(form.startTimeFormat));
    const createdTimeFormat = JSON.parse(JSON.stringify(form.createdTimeFormat));
    const updatedTimeFormat = JSON.parse(JSON.stringify(form.updatedTimeFormat));
    
    // 更新配置对象
    config.general.language = form.language;
    config.general.externalLinkOpenMode = form.externalLinkOpenMode;
    
    config.editor.uploadUrl = form.uploadUrl;
    config.editor.token = form.token;
    config.editor.defaultEditorMode = form.defaultEditorMode;
    config.editor.autoSave = form.autoSave;
    config.editor.autoSaveInterval = form.autoSaveInterval;
    
    config.appearance.theme = form.theme;
    config.appearance.fontSize = form.fontSize;
    config.appearance.fontFamily = form.fontFamily;

    // 更新特定字段时间格式设置
    config.general.startTimeFormat = startTimeFormat;
    config.general.createdTimeFormat = createdTimeFormat;
    config.general.updatedTimeFormat = updatedTimeFormat;
    
    // 保存配置到electron
    const success = await saveConfig(config);
    
    if (success) {
      // 同时保存本地设置，用于页面大小等UI相关设置
      // 这些设置不需要存储在electron配置中
      const localSettings = {
        pageSize: form.pageSize,
        pageSizeOptions: form.pageSizeOptions,
        maxLoadPages: form.maxLoadPages,
        externalLinkOpenMode: form.externalLinkOpenMode,
        // 添加特定时间格式设置
        startTimeFormat,
        createdTimeFormat,
        updatedTimeFormat
      };
      
      localStorage.setItem('general-settings', JSON.stringify(localSettings));
      
      // 重新加载配置以确保表单显示的是最新保存的数据
      await loadSettings();
      
      // 保存完成后更新初始配置状态
      setInitialFormState();
      
      ElMessage.success(t('settings.saveSuccess'));
    } else {
      ElMessage.error(t('common.saveFailed'));
    }
  } catch (error) {
    console.error('保存设置失败:', error);
    ElMessage.error(t('common.saveFailed'));
  }
};

// 存储初始表单状态用于比较是否有修改
const initialFormState = ref({});

// 设置初始表单状态
const setInitialFormState = () => {
  initialFormState.value = JSON.stringify(form);
};

// 检查是否有未保存的修改
const hasUnsavedChanges = () => {
  const currentFormState = JSON.stringify(form);
  return currentFormState !== initialFormState.value;
};

// 重置设置
const resetSettings = async () => {
  try {
    ElMessageBox.confirm(
      t('settings.resetConfirm'),
      t('settings.resetTitle'),
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning',
      }
    ).then(async () => {
      // 重置为默认值，避免使用可能不存在的属性
      form.language = 'zh-CN';
      form.pageSize = 15;
      form.pageSizeOptions = [10, 15, 20, 50];
      form.maxLoadPages = 10;
      form.externalLinkOpenMode = 'browser' as 'browser' | 'internal';
      form.uploadUrl = '';
      form.token = '';
      form.defaultEditorMode = 'richText';
      form.autoSave = true;
      form.autoSaveInterval = 5;
      form.theme = 'system';
      form.fontSize = 'medium';
      form.fontFamily = 'system';

      // 获取默认配置
      const config = await getConfig();
      
      // 重置特定字段时间格式设置（使用深拷贝避免引用问题）
      form.startTimeFormat = JSON.parse(JSON.stringify(config.general.startTimeFormat));
      form.createdTimeFormat = JSON.parse(JSON.stringify(config.general.createdTimeFormat));
      form.updatedTimeFormat = JSON.parse(JSON.stringify(config.general.updatedTimeFormat));
      
      // 直接保存重置后的设置
      await saveSettings();
      
      ElMessage.success(t('settings.resetSuccess'));
    }).catch(() => {
      // 用户取消操作
    });
  } catch (error) {
    console.error('重置设置失败:', error);
  }
};

// 从electron配置和localStorage加载设置
const loadSettings = async () => {
  try {
    // 从electron获取配置
    const config = await getConfig();
    
    // 设置通用配置
    form.language = config.general.language;
    form.externalLinkOpenMode = (config.general.externalLinkOpenMode || 'browser') as 'browser' | 'internal';
    
    // 设置编辑器配置
    form.uploadUrl = config.editor.uploadUrl;
    form.token = config.editor.token;
    form.defaultEditorMode = config.editor.defaultEditorMode;
    form.autoSave = config.editor.autoSave;
    form.autoSaveInterval = config.editor.autoSaveInterval;
    
    // 设置外观配置
    form.theme = config.appearance.theme;
    form.fontSize = config.appearance.fontSize;
    form.fontFamily = config.appearance.fontFamily;
    
    // 设置特定字段时间格式
    if (config.general.startTimeFormat) {
      form.startTimeFormat = JSON.parse(JSON.stringify(config.general.startTimeFormat));
    }
    if (config.general.createdTimeFormat) {
      form.createdTimeFormat = JSON.parse(JSON.stringify(config.general.createdTimeFormat));
    }
    if (config.general.updatedTimeFormat) {
      form.updatedTimeFormat = JSON.parse(JSON.stringify(config.general.updatedTimeFormat));
    }

    // 从localStorage加载UI相关设置
    const generalSettings = localStorage.getItem('general-settings');
    if (generalSettings) {
      try {
        const parsedSettings = JSON.parse(generalSettings);
        // 这些设置来自localStorage
        form.pageSize = parsedSettings.pageSize || 15;
        form.pageSizeOptions = parsedSettings.pageSizeOptions || [10, 15, 20, 50];
        form.maxLoadPages = parsedSettings.maxLoadPages || 10;
        // 加载外部链接打开方式（以localStorage中的为准，因为可能更新）
        if (parsedSettings.externalLinkOpenMode) {
          form.externalLinkOpenMode = parsedSettings.externalLinkOpenMode as 'browser' | 'internal';
        }
        
        // 再次从localStorage加载特定时间格式（以localStorage中的为准，因为可能更新）
        if (parsedSettings.startTimeFormat) {
          form.startTimeFormat = parsedSettings.startTimeFormat;
        }
        if (parsedSettings.createdTimeFormat) {
          form.createdTimeFormat = parsedSettings.createdTimeFormat;
        }
        if (parsedSettings.updatedTimeFormat) {
          form.updatedTimeFormat = parsedSettings.updatedTimeFormat;
        }
      } catch (error) {
        console.error('Failed to parse general settings:', error);
      }
    }
    
    // 保存初始状态（用于比较是否有未保存的更改）
    setInitialFormState();
  } catch (error) {
    console.error('加载设置失败:', error);
    ElMessage.error(t('settings.loadFailed'));
  }
};

// 返回上一页
const goBack = () => {
  if (hasUnsavedChanges()) {
    ElMessageBox.confirm(
      t('settings.unsavedChangesMessage'),
      t('settings.unsavedChangesTitle'),
      {
        confirmButtonText: t('settings.exit'),
        cancelButtonText: t('settings.stayOnPage'),
        type: 'warning',
      }
    ).then(() => {
      // 用户选择退出，清除表单缓存
      router.back();
    }).catch(() => {
      // 用户选择留在页面，不做任何处理
    });
  } else {
    router.back();
  }
};

// 组件挂载时加载设置
onMounted(() => {
  loadSettings();
  loadBuckets(); // 加载桶名称列表
});

// 每次组件被激活时重新加载设置
onActivated(() => {
  loadSettings();
  loadBuckets(); // 同时重新加载桶名称列表
});

// 每次激活组件时重新加载设置
watch(() => route.path, () => {
  if (route.path === '/settings') {
    loadSettings();
  }
});

// 格式化日期时间显示
const formatDateTime = (dateStr: string) => {
  try {
    return formatTimeFieldSync(dateStr, 'general');
  } catch (error) {
    console.error('日期格式化错误:', error);
    return dateStr;
  }
};

// 添加自定义分页大小
const addCustomPageSize = () => {
  if (customPageSize.value && !form.pageSizeOptions.includes(customPageSize.value)) {
    form.pageSizeOptions.push(customPageSize.value);
    // 对选项进行排序
    form.pageSizeOptions.sort((a, b) => a - b);
    // 清空输入
    customPageSize.value = undefined;
  }
};

// 添加默认选项
const addDefaultOption = (option: number) => {
  if (!form.pageSizeOptions.includes(option)) {
    form.pageSizeOptions.push(option);
    // 对选项进行排序
    form.pageSizeOptions.sort((a, b) => a - b);
  }
};

// 移除分页选项
const removePageSizeOption = (option: number) => {
  form.pageSizeOptions = form.pageSizeOptions.filter(o => o !== option);
};

// 修复customPageSize.value = null的类型问题
const clearCustomPageSize = () => {
  // 使用undefined而不是null
  customPageSize.value = undefined;
};
</script>

<style scoped>
html, body {
  margin: 0;
  padding: 0;
  overflow: hidden;
  height: 100%;
  width: 100%;
}

.settings-page {
  display: flex;
  height: 100vh;
  width: 100%;
  background-color: #f8f9fa;
  overflow: hidden;
  position: fixed;
  inset: 0;
  box-sizing: border-box;
}

.settings-sidebar {
  width: 280px;
  background-color: #fff;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
  height: 100%;
  overflow-y: auto;
  z-index: 10;
}

.sidebar-header {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.back-button {
  width: 32px;
  height: 32px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-right: 12px;
}

.back-button:hover {
  background-color: #f2f6fc;
}

.sidebar-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
}

.settings-menu {
  flex: 1;
  border-right: none;
}

.settings-content {
  flex: 1;
  padding: 32px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  min-width: 0;
  box-sizing: border-box;
  height: 100%;
  width: calc(100% - 280px);
}

.settings-section {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
  margin-bottom: 24px;
  width: 100%;
  box-sizing: border-box;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  margin-top: 0;
  margin-bottom: 16px;
  color: #303133;
}

.form-item-tip {
  display: none;
}

.settings-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 24px;
  margin-bottom: 24px;
  width: 100%;
  box-sizing: border-box;
}

.input-addon {
  margin-left: 8px;
  color: #606266;
}

.about-content {
  text-align: center;
  padding: 30px 0;
  max-width: 600px;
  margin: 0 auto;
}

.app-logo {
  margin-bottom: 16px;
}

.version {
  color: #909399;
  margin: 8px 0 16px;
}

.about-links {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 24px;
}

.about-links a {
  color: #409eff;
  text-decoration: none;
}

.about-links a:hover {
  text-decoration: underline;
}

@media (max-width: 768px) {
  .settings-page {
    flex-direction: column;
    overflow-y: auto;
  }
  
  .settings-sidebar {
    width: 100%;
    height: auto;
    max-height: none;
    overflow-y: visible;
  }
  
  .settings-content {
    padding: 20px;
    width: 100%;
    height: auto;
  }
  
  .settings-section {
    padding: 20px;
  }
}

/* 针对暗色主题适配 */
@media (prefers-color-scheme: dark) {
  .settings-page {
    background-color: #1a1a1a;
  }
  
  .settings-sidebar, 
  .settings-section {
    background-color: #262626;
    border-color: #333;
  }
  
  .sidebar-header,
  .settings-menu {
    border-color: #333;
  }
  
  .back-button:hover {
    background-color: #3a3a3a;
  }
  
  .section-title {
    color: #e0e0e0;
  }
  
  .form-item-tip {
    color: #a0a0a0;
  }
}

.scrollable-content {
  overflow-y: auto;
  flex: 1;
  padding-right: 16px;
}

/* 桶管理样式 */
.bucket-table-container {
  margin-top: 20px;
}

.bucket-add {
  display: flex;
  gap: 12px;
  margin-top: 20px;
  margin-bottom: 20px;
}

.bucket-add .el-input {
  width: 80%;
}

.page-size-options-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #eaeaea;
}

.page-size-select-area {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px;
  background-color: #fff;
  border-radius: 4px;
  min-height: 36px;
  border: 1px dashed #dcdfe6;
}

.page-size-tag {
  margin: 0;
}

.custom-page-size {
  display: flex;
  align-items: center;
  gap: 8px;
}

.custom-page-size .el-input-number {
  width: 120px;
}

.quick-options {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px 0;
  border-top: 1px solid #eaeaea;
}

.quick-option-label {
  font-weight: 600;
  color: #606266;
  margin-right: 8px;
}

.quick-option-button {
  margin: 0;
}

/* 适配暗色主题 */
@media (prefers-color-scheme: dark) {
  .page-size-options-container {
    background-color: #2d2d2d;
    border-color: #444;
  }

  .tag-list {
    background-color: #333;
    border-color: #555;
  }

  .quick-options {
    border-color: #444;
  }

  .quick-option-label {
    color: #aaa;
  }
}

/* 为输入框和数字输入框添加更多空间 */
.el-input, .el-input-number {
  margin-bottom: 5px;
}

/* 设置标签与输入控件之间的间距 */
:deep(.el-form-item__label) {
  padding-right: 15px;
}

/* 增加表单项之间的间距 */
:deep(.el-form-item) {
  margin-bottom: 24px;
}

/* 优化 radio 组样式 */
:deep(.el-radio) {
  margin-right: 20px;
  margin-bottom: 8px;
}

/* 添加问号图标样式 */
.tip-icon {
  margin-left: 8px;
  font-size: 16px;
  color: #909399;
  cursor: pointer;
  vertical-align: middle;
}

/* 暗黑模式下图标颜色适配 */
@media (prefers-color-scheme: dark) {
  .tip-icon {
    color: #a0a0a0;
  }
}
</style>